import 'package:flutter/foundation.dart';
import '../services/database_helper.dart';
import '../models/product.dart';

class ProductProvider with ChangeNotifier {
  List<Product> _products = [];
  bool _isLoading = false;

  List<Product> get products => _products;
  bool get isLoading => _isLoading;

  final DatabaseHelper _dbHelper = DatabaseHelper();

  // 加载某个饭店的所有商品
  Future<void> loadProductsByRestaurant(int restaurantId) async {
    _isLoading = true;
    notifyListeners();
    
    try {
      final products = await _dbHelper.getProductsByRestaurant(restaurantId);
      _products = products;
    } catch (e) {
      print('加载商品数据失败: $e');
      _products = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 添加商品
  Future<bool> addProduct(Product product) async {
    try {
      // 检查名称是否重复
      final isDuplicate = await _dbHelper.isProductNameDuplicate(
        product.restaurantId, 
        product.name
      );
      
      if (isDuplicate) {
        throw Exception('商品名称"${product.name}"已存在，请使用其他名称');
      }
      
      await _dbHelper.insertProduct(product);
      await loadProductsByRestaurant(product.restaurantId);
      return true;
    } catch (e) {
      print('添加商品失败: $e');
      rethrow;
    }
  }

  // 更新商品
  Future<bool> updateProduct(Product product) async {
    try {
      // 检查名称是否重复（排除自身）
      final isDuplicate = await _dbHelper.isProductNameDuplicate(
        product.restaurantId, 
        product.name,
        excludeId: product.id,
      );
      
      if (isDuplicate) {
        throw Exception('商品名称"${product.name}"已存在，请使用其他名称');
      }
      
      await _dbHelper.updateProduct(product);
      await loadProductsByRestaurant(product.restaurantId);
      return true;
    } catch (e) {
      print('更新商品失败: $e');
      rethrow;
    }
  }

  // 删除商品
  Future<bool> deleteProduct(int id, int restaurantId) async {
    try {
      await _dbHelper.deleteProduct(id);
      await loadProductsByRestaurant(restaurantId);
      return true;
    } catch (e) {
      print('删除商品失败: $e');
      rethrow;
    }
  }

  // 清空商品列表（当离开饭店详情页时调用）
  void clearProducts() {
    _products = [];
    notifyListeners();
  }
}